﻿package com.mixmedia.navigation {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import com.asual.swfaddress.SWFAddress;
	import com.asual.swfaddress.SWFAddressEvent;
	import com.mixmedia.navigation.Navigation;
	import com.mixmedia.navigation.NavigationEvent;	
	/**	 * @author colin
	 * 
	 * combine function of SWFAddress and com.mixmedia.navigation
	 * more information on SWFAddress:
	 * http://www.asual.com/swfaddress/
	 * 
	 * 
	 * To use this class, 
	 * 1. copy swfaddress.html and swfaddress.js to the script folder
	 * 2. link the script to index.html
	 * for more information, please check http://demo.mixmedia.com/swfAddress/adobe/
	 * 
	 */	class DeepLinking extends EventDispatcher {
		static private var ins:DeepLinking;
		private var iid : Number;
	
		static public function instance():DeepLinking{
			if(ins==null)ins = new DeepLinking();
			return ins;
			}						private var base : SWFAddress;			private var isNavChange:Boolean = false;
	
		private function DeepLinking() {
			Navigation.instance().when(NavigationEvent.CHANGE, this, setSWFAddressValue);
			base = new SWFAddress();
			base.addEventListener(SWFAddressEvent.CHANGE, onBaseChange, false, 0, true);
		}
		
		private function setSWFAddressValue(e:NavigationEvent):void{
			if(e.isSuppress==true)return;
			isNavChange = true;
	
			//string of target container representation
			var str:String = (e.targetContainer==""||e.targetContainer==null)?"" : "." + e.targetContainer;
			base.setValue(e.navKey+str);
		}
	
		private function onBaseChange():void{
			clearInterval(iid);
			iid = setInterval(delayDispatchBaseChange,5);
		}
		
		private function delayDispatchBaseChange():void{
			clearInterval(iid);
			if(isNavChange == true){
				isNavChange = false;
				return;
			}
			dispatchEvent(new Event(Event.CHANGE));
		}
	
		public function getBaseURL():String{
			return base.getBaseURL();
		}
	
		public function back():void {
			base.back();
	    }
	
	    public function forward():void {
	    	base.forward();
	    }
	    
	    public function go(delta:Number):void {
			base.go(delta);
	    }
	
	    public function href(url:String, target:String):void {
	    	base.href(url,target);
	    }
	
	    public function popup(url:String, name:String, options:String, handler:String):void {
	    	base.popup(url, name, options, handler);
		}
	
		public function getValue() : String {
			return SWFAddress.getValue();
		}
	}
}